import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_deer/login/iview/login_sms_iview.dart';
import 'package:flutter_deer/login/presenter/login_sms_presenter.dart';
import 'package:flutter_deer/login/provider/sms_send_provider.dart';
import 'package:flutter_deer/login/widgets/my_text_field.dart';
import 'package:flutter_deer/mvp/base_page.dart';
import 'package:flutter_deer/mvp/power_presenter.dart';
import 'package:flutter_deer/net/base_entity.dart';
import 'package:flutter_deer/res/resources.dart';
import 'package:flutter_deer/routers/fluro_navigator.dart';
import 'package:flutter_deer/routers/routers.dart';
import 'package:flutter_deer/shop/models/user_entity.dart';
import 'package:flutter_deer/util/change_notifier_manage.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/util/toast_utils.dart';
import 'package:flutter_deer/widgets/my_app_bar.dart';
import 'package:flutter_deer/widgets/my_button.dart';
import 'package:flutter_deer/widgets/my_scroll_view.dart';
import 'package:flutter_gen/gen_l10n/deer_localizations.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';

import '../login_router.dart';

/// design/1注册登录/index.html#artboard4
class SMSLoginPage extends StatefulWidget {
  const SMSLoginPage({super.key});

  @override
  _SMSLoginPageState createState() => _SMSLoginPageState();
}

class _SMSLoginPageState extends State<SMSLoginPage> with ChangeNotifierMixin<SMSLoginPage>,BasePageMixin<SMSLoginPage, PowerPresenter> implements LoginSmsIMvpView {

  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _vCodeController = TextEditingController();
  final FocusNode _nodeText1 = FocusNode();
  final FocusNode _nodeText2 = FocusNode();
  bool _clickable = false;
  late LoginSmsPagePresenter loginSmsPagePresenter;
  SmsSendProvider provider = SmsSendProvider();

  @override
  PowerPresenter<dynamic> createPresenter() {
    final PowerPresenter<dynamic> powerPresenter = PowerPresenter<dynamic>(
        this);
    loginSmsPagePresenter = new LoginSmsPagePresenter();
    powerPresenter.requestPresenter([loginSmsPagePresenter]);
    return powerPresenter;
  }

  @override
  void setLoginSmsCode(OperatorBaseEntity? result){
    provider.setSendResult(result);
    if(result!.data==false){
      showToast(result.message.nullSafe);
    }
  }

  @override
  void setUserToken(UserTokenEntity? entity){
    if(entity!.perfect=='1') {
      NavigatorUtils.push(context, Routes.home, clearStack: true);
    }else if(entity!.perfect=='0'){
      NavigatorUtils.push(context, LoginRouter.userInfoAuditPage, clearStack: true);
    }
  }

  @override
  Map<ChangeNotifier, List<VoidCallback>?>? changeNotifier() {
    final List<VoidCallback> callbacks = <VoidCallback>[_verify];
    return <ChangeNotifier, List<VoidCallback>?>{
      _phoneController: callbacks,
      _vCodeController: callbacks,
      _nodeText1: null,
      _nodeText2: null,
    };
  }

  void _verify() {
    final String name = _phoneController.text;
    final String vCode = _vCodeController.text;
    bool clickable = true;
    if (name.isEmpty || name.length < 9) {
      clickable = false;
    }
    if (vCode.isEmpty || vCode.length < 6) {
      clickable = false;
    }
    if (clickable != _clickable) {
      setState(() {
        _clickable = clickable;
      });
    }
  }

  void _login() {
    if(_phoneController.text.trim().nullSafe.startsWith('0')){
      loginSmsPagePresenter.loginBySmsCode(_phoneController.text
          .trim()
          .nullSafe, _vCodeController.text
          .trim()
          .nullSafe);
    }else {
      showToast('${DeerLocalizations.of(context)!.mobileStartError}');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: const MyAppBar(),
      body: MyScrollView(
        keyboardConfig: Utils.getKeyboardActionsConfig(context, <FocusNode>[_nodeText1, _nodeText2]),
        padding: const EdgeInsets.only(left: 16.0, right: 16.0, top: 20.0),
        children: _buildBody(),
      ),
    );
  }

  List<Widget> _buildBody() {
    return <Widget>[
      Text(
        DeerLocalizations.of(context)!.verificationCodeLogin,
        style: TextStyles.textBold26,
      ),
      Gaps.vGap16,
      MyTextField(
        focusNode: _nodeText1,
        controller: _phoneController,
        keyboardType: TextInputType.phone,
        hintText: DeerLocalizations.of(context)!.inputPhoneHint,
      ),
      Gaps.vGap8,
    ChangeNotifierProvider<SmsSendProvider>(
    create: (_) => provider,
    child: Consumer<SmsSendProvider>(
    builder: (_,provider,child){
      return MyTextField(
        focusNode: _nodeText2,
        controller: _vCodeController,
        maxLength: 6,
        keyboardType: TextInputType.number,
        hintText: DeerLocalizations.of(context)!.inputVerificationCodeHint,
        getVCode: () async {
          if (_phoneController.text.trim().length == 11||_phoneController.text.trim().length == 10||_phoneController.text.trim().length == 9) {
            if(_phoneController.text.trim().nullSafe.startsWith('0')){
              loginSmsPagePresenter.sendLoginSmsCode(
                  _phoneController.text.trim().nullSafe);
              return Future<bool>.value(provider.send);
            }else {
              showToast('${DeerLocalizations.of(context)!.mobileStartError.nullSafe}');
              return false;
            }
          } else {
            Toast.show(DeerLocalizations.of(context)!.inputPhoneInvalid.nullSafe);
            return false;
          }

          Toast.show(DeerLocalizations.of(context)!.getVerificationCode);
          return Future<bool>.value(true);
        },
      );
    })),
      Gaps.vGap8,
      Container(
        alignment: Alignment.centerLeft,
        child: RichText(
          text: TextSpan(
            text: DeerLocalizations.of(context)!.registeredTips,
            style: Theme.of(context).textTheme.titleSmall?.copyWith(fontSize: Dimens.font_sp14),
            children: <TextSpan>[
              TextSpan(
                text: DeerLocalizations.of(context)!.register,
                style: TextStyle(
                  color: Theme.of(context).colorScheme.error,
                ),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    NavigatorUtils.push(context, LoginRouter.registerPage);
                  },
              ),
              TextSpan(text: Utils.getCurrLocale() == 'zh' ? '。' : '.',),
            ],
          ),
        ),
      ),
      Gaps.vGap24,
      MyButton(
        onPressed: _clickable ? _login : null,
        text: DeerLocalizations.of(context)!.login,
      ),
      Container(
        height: 40.0,
        alignment: Alignment.centerRight,
        child: GestureDetector(
          child: Text(
            DeerLocalizations.of(context)!.forgotPasswordLink,
            style: Theme.of(context).textTheme.titleSmall,
          ),
          onTap: () => NavigatorUtils.push(context, LoginRouter.resetPasswordPage),
        ),
      )
    ];
  }
}
